﻿using Basic.FlowApplication.Extend;
using Basic.FlowApplication.Interface;
using Basic.FlowApplication.Model;
using Basic.FlowApplication.Model.AuditLog;
using Basic.FlowRemoteModel;
using Basic.FlowRemoteModel.Application.Model;
using WeDonekRpc.Client.Attr;
using WeDonekRpc.Helper;

namespace Basic.FlowApplication.AuditEvent
{
    [IocName("Audit_3")]
    [ClassLifetimeAttr(ClassLifetimeType.SingleInstance)]
    internal class RejectModifyEvent : IItemAuditEvent
    {
        public AfootAuditLogItem ItemAudit ( AuditFlowBody flow, FlowAuditLogState log, AuditRes result )
        {
            AfootAuditLogItem item = log.LogItem.Find(a => a.Id == result.ItemId);
            item.CheckAuditItem(result);
            FlowNode node = flow.Nodes[item.NodeId];
            if ( ( FlowAuditButton.打回修改 & node.AuditButton ) != FlowAuditButton.打回修改 )
            {
                throw new ErrorException("flow.audit.not.allow.reject");
            }
            item.AuditState = FlowAuditItemStatus.打回修改;
            item.AuditOpinion = result.Opinion;
            item.SignFileId = result.SignFileId;
            log.ToVoidItem(flow, flow.BeginNode, item.Id);
            FlowNode begin = flow.Nodes[flow.BeginNode];
            log.LogItem.Add(new AfootAuditLogItem
            {
                CompanyId = log.CompanyId,
                EmpByDeptId = log.CreateByDeptId,
                EmpByUnitId = log.CreateByUnitId,
                EmpId = log.CreateBy,
                RootNodeId = flow.BeginNode,
                RootBatchNo = null,
                PrevBackNo = item.BatchNo,
                PrevNodeId = item.NodeId,
                NodeId = begin.Id,
                NodeType = begin.NodeType,
                OptItemId = item.Id,
                MarkState = FlowItemMarkState.打回,
                TimeOut = begin.LimitTime.HasValue ? DateTime.Now.AddMinutes(begin.LimitTime.Value) : null
            });
            return item;
        }
    }
}
